import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  UploadedFile,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { CommunityService } from './community.service';
import { CreateCommunityDto } from './dto/create-community.dto';
import { UpdateCommunityDto } from './dto/update-community.dto';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiConsumes,
  ApiBody,
} from '@nestjs/swagger';
import { Community } from './entities/community.entity';
import { BufferedFile } from '../minio/file.model';

@ApiTags('社区管理')
@ApiBearerAuth()
@Controller('community')
export class CommunityController {
  constructor(private readonly communityService: CommunityService) {}

  @Post()
  @ApiOperation({ summary: '创建社区' })
  @ApiResponse({
    status: 201,
    description: '创建成功',
    type: Community,
  })
  create(@Body() createCommunityDto: CreateCommunityDto) {
    return this.communityService.create(createCommunityDto);
  }

  @Post('upload/:id')
  @ApiOperation({ summary: '上传社区图片' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(
    @Param('id') id: string,
    @UploadedFile() file: BufferedFile,
  ) {
    if (!file) {
      throw new BadRequestException('文件不能为空');
    }
    return this.communityService.uploadImage(+id, file);
  }

  @Get()
  @ApiOperation({ summary: '获取所有社区' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: [Community],
  })
  findAll() {
    return this.communityService.findAll();
  }

  @Get(':id')
  @ApiOperation({ summary: '获取指定社区' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: Community,
  })
  findOne(@Param('id') id: string) {
    return this.communityService.findOne(+id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新社区信息' })
  @ApiResponse({
    status: 200,
    description: '更新成功',
    type: Community,
  })
  update(
    @Param('id') id: string,
    @Body() updateCommunityDto: UpdateCommunityDto,
  ) {
    return this.communityService.update(+id, updateCommunityDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除社区' })
  @ApiResponse({
    status: 200,
    description: '删除成功',
  })
  remove(@Param('id') id: string) {
    return this.communityService.remove(+id);
  }
}
